﻿// PrivateChatDialog.cpp : implementation file
//

#include "stdafx.h"
#include "ChatConferencesClient.h"
#include "PrivateChatDialog.h"


// CPrivateChatDialog dialog

///<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
bool CPrivateChatDialog::initPrivateChat(
	CString srcUser, CString dstUser, CString strServer, SOCKET socketParentWindows)
{
	this ->srcUser = srcUser;
	this ->dstUser = dstUser;
	this ->strServer = strServer;
	this ->socketParentWindows = socketParentWindows;

	return true;
}

int CPrivateChatDialog::createPackage(int code) {
	// package struture: username-0-code-username:seq-msg
	CString package = _T("");

	switch (code)
	{
		case 300: //Request for Private Chat include username
		{
			// gửi yêu cầu lên server chat private với username
			package += this ->srcUser;
			package += "-0-300-";
			package += this ->dstUser;
			package += ":seq-Hello";
			
			break;
		}
		case 301: //Send Message
		{
			CString message;
			GetDlgItemTextW(IDC_EDIT_MESSAGE, message);
			
			pListMessages ->AddString(this ->srcUser + _T(": ") + message);
			package += this ->srcUser;
			package += "-0-301-";
			package += this ->dstUser;
			package += ":seq-";
			package += message;

			break;
		}
		case 302: //Logoff mode Private Chat
		{
			package += this ->srcUser;
			package += "-0-302-";
			package += this ->dstUser;
			package += ":seq-Logoff";

			break;
		}
		
		case 999: // send to parent windows that i'm close 
			{
				package += this ->dstUser;
				package += "-1-999-";
				package += this ->srcUser;
				package += ":seq-Logoff";

				int _retcode = -1;
				int Len = package.GetLength();
				char* sendBuff = new char[Len+1];

				strncpy(sendBuff,CT2A(package), package.GetLength());
				sendBuff[Len]='\0';
				
				_retcode = send (this ->socketParentWindows, (char*)&Len, sizeof(int),0);
				_retcode = send (this ->socketParentWindows, (char*)sendBuff, Len,0);
				
				return _retcode;
			}

	}

	int retcode = -1;
	if (package != "" && !package.IsEmpty()) {
		retcode = sendPackage(package);
	}

	if (code == 302) {
		
	}

	return retcode;
}

int CPrivateChatDialog::sendPackage (CString msg) {
	int Len = msg.GetLength();
	char* sendBuff = new char[Len+1];

	strncpy(sendBuff,CT2A(msg), msg.GetLength());
	sendBuff[Len]='\0';
	
	//Send kich thuoc truoc
	int retcode;
	retcode = send(sClient, (char*)&Len, sizeof(int),0);
	retcode = send(sClient, (char*)sendBuff, Len, 0);
	
	return retcode;
}

BOOL CPrivateChatDialog::OnInitDialog()
{
	CDialog::OnInitDialog();

	this ->pListMessages = (CListBox*)GetDlgItem (IDC_LIST_MESSAGES);

	gSock = new CGlobalSocket ();
	gSock ->initSocket (this ->strServer);

	gSock->setServerAddress(this ->strServer);
	CString mess = gSock->connectToServer(this ->strServer);
	//MessageBox(mess);

	if( mess != "")
	{
		if(mess == _T("Connect Successful!"))
		{
			sClient = gSock->getSockClient();

			int err = WSAAsyncSelect(sClient, m_hWnd, WM_SOCKET, FD_READ|FD_ACCEPT|FD_CLOSE);
			
			if (err) {
				MessageBox(_T("Can't call WSAAsyncSelect"));
			}
		}
		else
		{
			MessageBox(mess);
		}
	}

	
	sReceivedMessage = _T("");
	sendType = 0;
	SetWindowTextW(_T("Private chat: " + srcUser + " <-> " + dstUser));
	
	createPackage (300);

	return true;
}

BOOL CPrivateChatDialog::PreTranslateMessage(MSG* pMsg) {
	// TODO: Add your specialized code here and/or call the base class
	if ( pMsg ->message == WM_KEYDOWN && pMsg ->wParam == VK_RETURN )
	{
		int idCtrl = this->GetFocus() ->GetDlgCtrlID();
		if ( idCtrl == IDC_EDIT_MESSAGE)
		{
			this ->OnBnClickedBtnSendMessage ();
		}
	}
	return CDialog::PreTranslateMessage(pMsg);
}

LRESULT CPrivateChatDialog::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) 
{
	// TODO: Add your specialized code here and/or call the base class
	if (message == WM_SOCKET){
		SockMsg (wParam, lParam);
	}
	return CDialog::WindowProc(message, wParam, lParam);
}
LRESULT CPrivateChatDialog::SockMsg(WPARAM wParam, LPARAM lParam)
{
	if (WSAGETSELECTERROR(lParam))
    {
		 // Display the error and close the socket
         closesocket(wParam);
    }
	switch(WSAGETSELECTEVENT(lParam))
    {
		case FD_READ:
			{
				if (!sendType){
					recv(sClient,(char*)&buffLength,sizeof(int),0);
					sendType=1;
				}
				else
				{
					char* buffer = new char[buffLength+1];
					recv (sClient,buffer,buffLength,0);

					buffer[buffLength]='\0';
					sendType=0;
					sReceivedMessage = buffer;
					delete buffer;
					vector<CString> res = CProcess::parseString(sReceivedMessage, '-');
					//MessageBox(sReceivedMessage);
					choseAction(res);
				}
				break;
			}
		case FD_CLOSE:
			{
				closesocket(wParam);
			}
			break;
	}
	return 0;
}

void CPrivateChatDialog::choseAction(vector<CString> arrReceivePackage) {
	PACKAGE pack = parseMessage(arrReceivePackage);

	switch (pack.Code) {
		case 400: {
			// Send Request Private chat for username
			// Nhận được yêu cầu chat private của user khác gửi tới,
			// lập tức hiện cửa sổ chat private

			// tìm xem có đang chat private với user đó hay k?
			
			// Đã xử lý tại chat room
			break;
				  }

		case 401: {
			// Send Message
			// Client nhận được message private từ user khác
			this ->pListMessages ->AddString (pack.sUsername + _T(": ") + pack.Message);

			break;
				  }

		case 402: {
			// Send Logoff mode private chat
			this ->pListMessages ->AddString (pack.sUsername + _T(" ") + pack.Message);
			CEdit *editSend = (CEdit *)GetDlgItem (IDC_EDIT_MESSAGE);
			//editSend ->ShowWindow (FALSE);
			editSend ->SetReadOnly (1);
			break;
				  }
	}
}

PACKAGE CPrivateChatDialog::parseMessage(std::vector<CString> arrCode)
{
	PACKAGE res;
	char *temp;
	int index;
	res.sUsername = arrCode[0];
	CProcess::ConvertCStringToChar(arrCode[1],temp);
	res.Type = atoi(temp);
	CProcess::ConvertCStringToChar(arrCode[2], temp);
	res.Code = atoi(temp);
	index = arrCode[3].Find(':');
	res.Destination = arrCode[3].Left(index);
	CProcess::ConvertCStringToChar(arrCode[3].Right(arrCode[2].GetLength() - (index + 1)),temp);
	res.Sequence = atoi(temp);
	res.Message = arrCode[4];

	int length = arrCode.size ();
	for (int idx = 5 ; idx < length; ++ idx) {
		res.Message += "-";
		res.Message += arrCode [idx];
	}

	return res;
}
///>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

IMPLEMENT_DYNAMIC(CPrivateChatDialog, CDialog)

CPrivateChatDialog::CPrivateChatDialog(CWnd* pParent /*=NULL*/)
	: CDialog(CPrivateChatDialog::IDD, pParent)
{
	m_pParent = pParent;
}

CPrivateChatDialog::~CPrivateChatDialog()
{
}


void CPrivateChatDialog::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
}


BEGIN_MESSAGE_MAP(CPrivateChatDialog, CDialog)
	ON_BN_CLICKED(IDC_BTN_SEND_MESSAGE, &CPrivateChatDialog::OnBnClickedBtnSendMessage)
	ON_BN_CLICKED(IDC_BTN_SEND_FILE, &CPrivateChatDialog::OnBnClickedBtnSendFile)
	ON_WM_CLOSE()
END_MESSAGE_MAP()


// CPrivateChatDialog message handlers

void CPrivateChatDialog::OnBnClickedBtnSendMessage()
{
	// TODO: Add your control notification handler code here
	//CString msg;
	//int length = GetDlgItemTextW (IDC_EDIT_MESSAGE, msg);	
	
	createPackage(301);
	SetDlgItemTextW(IDC_EDIT_MESSAGE, _T(""));

	//MessageBox (msg);
}

void CPrivateChatDialog::OnBnClickedBtnSendFile()
{
	// TODO: Add your control notification handler code here
	MessageBox (_T("Tuấn & Lâm will be continue..."));
}

void CPrivateChatDialog::OnClose()
{
	// TODO: Add your message handler code here and/or call default
	if (MessageBox(_T("Are you sure?"), _T("Exit"), MB_YESNO) == IDYES) {
		createPackage (302);
		//createPackage (999);// send to parent windows that i'm close

		CDialog::OnClose();	
	}
}
